package com.study.langchain4j.config.nosql.redis;

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author xl-9527
 * @since 2025/10/31
 */
@Configuration(proxyBeanMethods = false)
public class RedisConfig {

    @Bean
    RedisTemplate<String, Object> redisTemplate(final RedisConnectionFactory redisConnectionFactory, final ObjectMapper objectMapper) {
        final ObjectMapper redisObjectMapper = objectMapper.copy();
        this.initRedisJackSonConfig(redisObjectMapper);
        final RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        final GenericJackson2JsonRedisSerializer jsonRedisSerializer = new GenericJackson2JsonRedisSerializer(redisObjectMapper);
        final StringRedisSerializer stringSerializer = new StringRedisSerializer();
        // value serializer
        redisTemplate.setValueSerializer(jsonRedisSerializer);
        redisTemplate.setHashValueSerializer(jsonRedisSerializer);
        // key serializer
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    private void initRedisJackSonConfig(final ObjectMapper objectMapper) {
        // 序列化的时候设置 class 信息
        objectMapper.activateDefaultTyping(
                LaissezFaireSubTypeValidator.instance,
                ObjectMapper.DefaultTyping.NON_FINAL,
                JsonTypeInfo.As.PROPERTY // 使用一个属性来存储类型信息，默认为 "@class"
        );
    }
}
